﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace WebCoreAdmin.Common
{
    /// <summary>
    ///     RSA加解密 使用OpenSSL的公钥加密/私钥解密
    ///     作者：李志强
    ///     创建时间：2017年10月30日15:50:14
    ///     QQ:501232752
    ///     提示：PKCS1生成2048位
    ///     配套htmljavascript：http://travistidwell.com/jsencrypt/index.html
    ///     <example>
    ///         public static string Pub
    ///         =@"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsm9r+noXyrrJ2XIMiNckXna+y6yg/uA9sEmKP2ub4TGFdIkRgiLYRMGo2+D5Iu8byYwZZIzqVlU43RDeLBLXKdb92zdqEouhnHXw5jJ482G4gJTKMI0yAq8HDv3C8i2sk4ZvmJChVs7m5Frpik+6PdUagEwhgtot14f/e1lXBtAG8Pn5WLG9+SaM0z/UFmH3hRjt85VObXVG3BHZ+DBnzKQD3i7FxeblzK2mpASO0cW0wEqym4xUYGQ+yCeoJwnv1s7YqBtJqB15ztQsYMTD5UxNk3fKXw8rgId2qpi+EU15vwXTpBCQ0l1iRS8vI2Z1Y392WIe/Kilwrjkq5YougwIDAQAB";
    ///         public static string Pri =
    ///         @"MIIEpAIBAAKCAQEAsm9r+noXyrrJ2XIMiNckXna+y6yg/uA9sEmKP2ub4TGFdIkRgiLYRMGo2+D5Iu8byYwZZIzqVlU43RDeLBLXKdb92zdqEouhnHXw5jJ482G4gJTKMI0yAq8HDv3C8i2sk4ZvmJChVs7m5Frpik+6PdUagEwhgtot14f/e1lXBtAG8Pn5WLG9+SaM0z/UFmH3hRjt85VObXVG3BHZ+DBnzKQD3i7FxeblzK2mpASO0cW0wEqym4xUYGQ+yCeoJwnv1s7YqBtJqB15ztQsYMTD5UxNk3fKXw8rgId2qpi+EU15vwXTpBCQ0l1iRS8vI2Z1Y392WIe/Kilwrjkq5YougwIDAQABAoIBAEd6ZOngsNkwPB2UFztV26bPsJyMWa3gDDYrL2s6YyYxnUFSiyXzaWkZntf95i89U4d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jeAnRwLvCowOndc60Z4SRV7XCeYTqdAZDqauq3AkBlyWuDAu1+xK7lU9OULyEaqRBeNpjRoQ==";
    ///         var rsa = new RSAHelper(RSAHelper.RSAType.RSA2, Encoding.UTF8, s.pri, s.pub);
    ///         string str = "博客园 http://www.cnblogs.com/";
    ///         Console.WriteLine("原始字符串：" + str);
    ///         //加密
    ///         string enStr = rsa.Encrypt(str);
    ///         Console.WriteLine("加密字符串：" + enStr);
    ///         //解密
    ///         string deStr = rsa.Decrypt(enStr);
    ///         Console.WriteLine("解密字符串：" + deStr);
    ///         //私钥签名
    ///         string signStr = rsa.Sign(str);
    ///         Console.WriteLine("字符串签名：" + signStr);
    ///         //公钥验证签名
    ///         bool signVerify = rsa.Verify(str, signStr);
    ///         Console.WriteLine("验证签名：" + signVerify);
    ///     </example>
    /// </summary>
    public class RsaHelper
    {
        /// <summary>
        ///     RSA算法类型
        /// </summary>
        public enum RsaType
        {
            /// <summary>
            ///     SHA1
            /// </summary>
            Rsa = 0,

            /// <summary>
            ///     RSA2 密钥长度至少为2048
            ///     SHA256
            /// </summary>
            Rsa2
        }

        private readonly Encoding _encoding;
        private readonly HashAlgorithmName _hashAlgorithmName;

        private readonly RSA _privateKeyRsaProvider;
        private readonly RSA _publicKeyRsaProvider;

        /// <summary>
        ///     实例化RSAHelper
        /// </summary>
        /// <param name="rsaType">加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048</param>
        /// <param name="encoding">编码类型</param>
        /// <param name="privateKey">私钥</param>
        /// <param name="publicKey">公钥</param>
        public RsaHelper(RsaType rsaType, Encoding encoding, string privateKey, string publicKey = null)
        {
            _encoding = encoding;
            if (!string.IsNullOrEmpty(privateKey)) _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);

            if (!string.IsNullOrEmpty(publicKey)) _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);

            _hashAlgorithmName = rsaType == RsaType.Rsa ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256;
        }

        #region 使用私钥签名

        /// <summary>
        ///     使用私钥签名
        /// </summary>
        /// <param name="data">原始数据</param>
        /// <returns></returns>
        public string Sign(string data)
        {
            var dataBytes = _encoding.GetBytes(data);

            var signatureBytes =
                _privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1);

            return Convert.ToBase64String(signatureBytes);
        }

        #endregion

        #region 使用公钥验证签名

        /// <summary>
        ///     使用公钥验证签名
        /// </summary>
        /// <param name="data">原始数据</param>
        /// <param name="sign">签名</param>
        /// <returns></returns>
        public bool Verify(string data, string sign)
        {
            var dataBytes = _encoding.GetBytes(data);
            var signBytes = Convert.FromBase64String(sign);

            var verify =
                _publicKeyRsaProvider.VerifyData(dataBytes, signBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1);

            return verify;
        }

        #endregion

        #region 解密

        public string Decrypt(string cipherText)
        {
            if (_privateKeyRsaProvider == null) throw new Exception("_privateKeyRsaProvider is null");

            return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText),
                RSAEncryptionPadding.Pkcs1));
        }

        #endregion

        #region 加密

        public string Encrypt(string text)
        {
            if (_publicKeyRsaProvider == null) throw new Exception("_publicKeyRsaProvider is null");

            return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text),
                RSAEncryptionPadding.Pkcs1));
        }

        #endregion

        #region 使用私钥创建RSA实例

        public RSA CreateRsaProviderFromPrivateKey(string privateKey)
        {
            var privateKeyBits = Convert.FromBase64String(privateKey);

            var rsa = RSA.Create();
            var rsaParameters = new RSAParameters();

            using (var binaryReader = new BinaryReader(new MemoryStream(privateKeyBits)))
            {
                var twoBytes = binaryReader.ReadUInt16();
                if (twoBytes == 0x8130)
                    binaryReader.ReadByte();
                else if (twoBytes == 0x8230)
                    binaryReader.ReadInt16();
                else
                    throw new Exception("Unexpected value read binaryReader.ReadUInt16()");

                twoBytes = binaryReader.ReadUInt16();
                if (twoBytes != 0x0102)
                    throw new Exception("Unexpected version");

                var bt = binaryReader.ReadByte();
                if (bt != 0x00)
                    throw new Exception("Unexpected value read binaryReader.ReadByte()");

                rsaParameters.Modulus = binaryReader.ReadBytes(GetIntegerSize(binaryReader));
                rsaParameters.Exponent = binaryReader.ReadBytes(GetIntegerSize(binaryReader));
                rsaParameters.D = binaryReader.ReadBytes(GetIntegerSize(binaryReader));
                rsaParameters.P = binaryReader.ReadBytes(GetIntegerSize(binaryReader));
                rsaParameters.Q = binaryReader.ReadBytes(GetIntegerSize(binaryReader));
                rsaParameters.DP = binaryReader.ReadBytes(GetIntegerSize(binaryReader));
                rsaParameters.DQ = binaryReader.ReadBytes(GetIntegerSize(binaryReader));
                rsaParameters.InverseQ = binaryReader.ReadBytes(GetIntegerSize(binaryReader));
            }

            rsa.ImportParameters(rsaParameters);
            return rsa;
        }

        #endregion

        #region 使用公钥创建RSA实例

        public RSA CreateRsaProviderFromPublicKey(string publicKeyString)
        {
            byte[] seqOid = {0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00};

            var x509Key = Convert.FromBase64String(publicKeyString);

            using (var mem = new MemoryStream(x509Key))
            {
                using (var binaryReader = new BinaryReader(mem))
                {
                    var twoBytes = binaryReader.ReadUInt16();
                    if (twoBytes == 0x8130)
                        binaryReader.ReadByte();
                    else if (twoBytes == 0x8230)
                        binaryReader.ReadInt16();
                    else
                        return null;

                    var seq = binaryReader.ReadBytes(15);
                    if (!CompareByteArrays(seq, seqOid))
                        return null;

                    twoBytes = binaryReader.ReadUInt16();
                    if (twoBytes == 0x8103
                    )
                        binaryReader.ReadByte();
                    else if (twoBytes == 0x8203)
                        binaryReader.ReadInt16();
                    else
                        return null;

                    var bt = binaryReader.ReadByte();
                    if (bt != 0x00)
                        return null;

                    twoBytes = binaryReader.ReadUInt16();
                    if (twoBytes == 0x8130)
                        binaryReader.ReadByte();
                    else if (twoBytes == 0x8230)
                        binaryReader.ReadInt16();
                    else
                        return null;

                    twoBytes = binaryReader.ReadUInt16();
                    byte lowByte;
                    byte highByte = 0x00;

                    if (twoBytes == 0x8102)
                    {
                        lowByte = binaryReader.ReadByte();
                    }
                    else if (twoBytes == 0x8202)
                    {
                        highByte = binaryReader.ReadByte();
                        lowByte = binaryReader.ReadByte();
                    }
                    else
                    {
                        return null;
                    }

                    byte[] modInt =
                        {lowByte, highByte, 0x00, 0x00};
                    var modSize = BitConverter.ToInt32(modInt, 0);

                    var firstByte = binaryReader.PeekChar();
                    if (firstByte == 0x00)
                    {
                        binaryReader.ReadByte();
                        modSize -= 1;
                    }

                    var modulus = binaryReader.ReadBytes(modSize);

                    if (binaryReader.ReadByte() != 0x02)
                        return null;
                    var expBytes = binaryReader.ReadByte();
                    var exponent = binaryReader.ReadBytes(expBytes);
                    var rsa = RSA.Create();
                    var rsaKeyInfo = new RSAParameters
                    {
                        Modulus = modulus,
                        Exponent = exponent
                    };
                    rsa.ImportParameters(rsaKeyInfo);

                    return rsa;
                }
            }
        }

        #endregion

        #region 导入密钥算法

        private int GetIntegerSize(BinaryReader binaryReader)
        {
            int count;
            var bt = binaryReader.ReadByte();
            if (bt != 0x02)
                return 0;
            bt = binaryReader.ReadByte();

            if (bt == 0x81)
            {
                count = binaryReader.ReadByte();
            }
            else if (bt == 0x82)
            {
                var highByte = binaryReader.ReadByte();
                var lowByte = binaryReader.ReadByte();
                byte[] modInt = {lowByte, highByte, 0x00, 0x00};
                count = BitConverter.ToInt32(modInt, 0);
            }
            else
            {
                count = bt;
            }

            while (binaryReader.ReadByte() == 0x00) count -= 1;

            binaryReader.BaseStream.Seek(-1, SeekOrigin.Current);
            return count;
        }

        private bool CompareByteArrays(byte[] a, byte[] b)
        {
            if (a.Length != b.Length)
                return false;
            var i = 0;
            foreach (var c in a)
            {
                if (c != b[i])
                    return false;
                i++;
            }

            return true;
        }

        #endregion
    }
}